package js.dwim.web;

import java.io.IOException;
import java.util.List;

import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import js.dwim.domain.CommSession;
import js.dwim.domain.MapNode;
import js.dwim.domain.Player;
import js.dwim.domain.WorldMap;
import js.dwim.server.Game;
import js.dwim.server.Persistence;

public class PulseUpdateServlet
        extends HttpServlet
{
    private static final long serialVersionUID = 1L;

    public void service( HttpServletRequest request, HttpServletResponse response )
            throws ServletException, IOException
    {
        PersistenceManager pm   = Persistence.getManager();
        WorldMap world 			= Game.getWorldMap();
        Query q                 = pm.newQuery( CommSession.class, "this.active == mode" );
        q.declareParameters( "java.lang.Boolean mode" );

        @SuppressWarnings( "unchecked" )
        List<CommSession> result = (List<CommSession>) q.execute( Boolean.TRUE );

        for ( CommSession session : result )
        {
        	Player player 		= session.getPlayer();
        	List<MapNode> nodes = world.getPlayerNodes( player );
        	
        	player.setFunds( player.getFunds() + nodes.size() );
        	
        	PersistenceManager man = JDOHelper.getPersistenceManager( player );
        	man.makePersistent( player );
        	
            XmppCommServlet.sendMessage( session, String.format( "UP\nFUNDS:%s", 
            		player.getFunds() ) );
        }
    }
}